package com.huawei.esdk.tp.interceptor;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.logging.Logger;

import org.apache.cxf.helpers.IOUtils;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingMessage;
import org.apache.cxf.io.CachedOutputStream;
import org.apache.cxf.message.Message;

import com.huawei.esdk.platform.common.bean.log.InterfaceLogBean;
import com.huawei.esdk.platform.common.utils.ApplicationContextUtil;
import com.huawei.esdk.platform.log.itf.IInterfaceLog;

public class TPSmcLoggingInInterceptor extends LoggingInInterceptor
{
    private static org.apache.log4j.Logger LOGGER = org.apache.log4j.Logger.getLogger(TPSmcLoggingInInterceptor.class);
    
    @Override
    protected void logging(Logger logger, Message message)
        throws Fault
    {
        String id = (String)message.getExchange().get(LoggingMessage.ID_KEY);
        if (id == null)
        {
            id = LoggingMessage.nextId();
            message.getExchange().put(LoggingMessage.ID_KEY, id);
        }
        message.put(LoggingMessage.ID_KEY, id);
        final LoggingMessage buffer = new LoggingMessage("Inbound Message\n----------------------------", id);
        
        Integer responseCode = (Integer)message.get(Message.RESPONSE_CODE);
        if (responseCode != null)
        {
            buffer.getResponseCode().append(responseCode);
        }
        
        String encoding = (String)message.get(Message.ENCODING);
        
        if (encoding != null)
        {
            buffer.getEncoding().append(encoding);
        }
        
        String ct = (String)message.get(Message.CONTENT_TYPE);
        if (ct != null)
        {
            buffer.getContentType().append(ct);
        }
        
        InputStream is = message.getContent(InputStream.class);
        if (is != null)
        {
            CachedOutputStream bos = new CachedOutputStream();
            try
            {
                IOUtils.copy(is, bos);
                
                bos.flush();
                File tempTile = bos.getTempFile();
                message.setContent(InputStream.class, bos.getInputStream());
                if (tempTile != null)
                {
                    // large thing on disk...
                    buffer.getMessage().append("\nMessage (saved to tmp file):\n");
                    buffer.getMessage().append("Filename: " + tempTile.getAbsolutePath() + "\n");
                }
                if (bos.size() > limit)
                {
                    buffer.getMessage().append("(message truncated to " + limit + " bytes)\n");
                }
                
                writePayload(buffer.getPayload(), bos, encoding, ct);
                
            }
            catch (Exception e)
            {
                throw new Fault(e);
            }
            finally
            {
                try
                {
                    if (null != is)
                    {
                        is.close();
                    }
                }
                catch (IOException e)
                {
                    LOGGER.error("handleMessage os close error", e);
                }
                try
                {
                    bos.close();
                }
                catch (IOException e)
                {
                    LOGGER.error("handleMessage os close error", e);
                }
            }
        }
        
        String strBuffer = buffer.toString();
        String resultCode = "HTTP" + responseCode;
        if (null != strBuffer)
        {
            int begin = 0;
            if (strBuffer.contains("<ErrCode>"))
            {
                begin = strBuffer.indexOf("<ErrCode>");
            }
            else
            {
                begin = -1;
            }
            
            if (-1 < begin)
            {
                begin += "<ErrCode>".length();
                int end = strBuffer.indexOf("</ErrCode>", begin);
                if (end > begin)
                {
                    resultCode = strBuffer.substring(begin, end);
                }
            }
        }
        
        InterfaceLogBean bean = new InterfaceLogBean();
        bean.setTransactionId(id);
        bean.setReq(false);
        bean.setRespTime(new Date());
        bean.setResultCode(resultCode);
        
        IInterfaceLog interfaceLogger = ApplicationContextUtil.getBean("interfaceLogger");
        interfaceLogger.info(bean);
    }
    
}
